<template>
  <view class="container">
    <view class="title">功能3：下载网络图片</view>
    <button class="btn" @click="downloadNetImage">点击下载图片</button>
    
    <!-- 显示下载进度和结果 -->
    <view v-if="progress > 0" class="progress-container">
      <text class="progress-tip">下载进度：{{ progress }}%</text>
      <view class="progress-bar">
        <view class="progress-fill" :style="{ width: progress + '%' }"></view>
      </view>
    </view>
    
    <!-- 显示下载的图片 -->
    <view v-if="downloadedUrl" class="image-container">
      <text class="image-tip">下载完成：</text>
      <image :src="downloadedUrl" class="downloaded-img" mode="widthFix" />
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';

// 存储下载进度（0-100）
const progress = ref(0);
// 存储下载完成的图片路径
const downloadedUrl = ref('');

// 下载网络图片
const downloadNetImage = () => {
  // 重置状态
  progress.value = 0;
  downloadedUrl.value = '';
  
  // 网络图片地址（示例图）
  const imageUrl = 'https://picsum.photos/800/500?random=1';
  
  // 调用UniApp下载文件API
  uni.downloadFile({
    url: imageUrl,
    success: (res) => {
      // 下载成功（状态码200）
      if (res.statusCode === 200) {
        downloadedUrl.value = res.tempFilePath; // 临时文件路径
        uni.showToast({ title: '下载完成', icon: 'success' });
      } else {
        uni.showToast({ title: '下载失败', icon: 'none' });
      }
    },
    fail: (err) => {
      console.error('下载失败：', err);
      uni.showToast({ title: '下载失败', icon: 'none' });
    },
    // 监听下载进度
    progress: (res) => {
      progress.value = res.progress; // 更新进度（0-100）
      console.log('当前进度：', progress.value + '%');
    }
  });
};
</script>

<style scoped>
.container {
  padding: 30rpx;
}
.title {
  font-size: 34rpx;
  font-weight: bold;
  margin-bottom: 40rpx;
  color: #333;
}
.btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 10rpx;
  font-size: 30rpx;
  margin-bottom: 30rpx;
}
.progress-container {
  margin-bottom: 30rpx;
}
.progress-tip {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}
.progress-bar {
  width: 100%;
  height: 12rpx;
  background-color: #eee;
  border-radius: 6rpx;
  overflow: hidden;
}
.progress-fill {
  height: 100%;
  background-color: #007aff;
  transition: width 0.3s;
}
.image-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}
.image-tip {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 15rpx;
}
.downloaded-img {
  width: 100%;
  border-radius: 8rpx;
}
</style>